import Vue from 'vue'
import md5 from 'js-md5'

/**
 * @param url 请求的url,应该包含请求参数(url的?后面的参数)
 * @param requestParams 请求参数(POST的JSON参数)
 * @returns {string} 获取签名
 */
Vue.prototype.$signature = function getSignature(url, requestParams) {
  var signString = "";
  var urlParams = parseQueryString(url);
  var requestBody = sortObject(mergeObject(urlParams, requestParams));
  for (var i in requestBody) {
    signString += i + requestBody[i];
  }
  return md5(md5(signString) + "LanPin123@.com").toUpperCase();
}

/**
 * @param url 请求的url
 * @returns {{}} 将url中请求参数组装成json对象(url的?后面的参数)
 */
function parseQueryString(url) {
  var urlReg = /^[^\?]+\?([\w\W]+)$/,
    paramReg = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
    urlArray = urlReg.exec(url),
    result = {};
  if (urlArray && urlArray[1]) {
    var paramString = urlArray[1], paramResult;
    while ((paramResult = paramReg.exec(paramString)) != null) {
      result[paramResult[1]] = paramResult[2];
    }
  }
  return result;
}

/**
 * @param object 传入要进行属性排序的对象
 * @returns {{}} 将对象进行属性排序(按首字母顺序进行排序)
 */
function sortObject(object) {
  var objectKeys = Object.keys(object).sort();
  var result = {};
  for (var i in objectKeys) {
    result[objectKeys[i]] = object[objectKeys[i]];
  }
  return result;
}

/**
 * @returns {*} 将两个对象合并成一个
 */
function mergeObject(objectOne, objectTwo) {
  if (objectTwo != null) {
    for (var key in objectTwo) {
      objectOne[key] = objectTwo[key]
    }
  }
  return objectOne;
}
